package club.xyes.zkh.ecommerce.security.entity;

import club.xyes.zkh.ecommerce.commons.context.ApplicationConstants;
import club.xyes.zkh.ecommerce.commons.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * Create by 郭文梁 2019/4/15 0015 16:02
 * SecurityUser
 * 安全验证需要的用户对象
 *
 * @author 郭文梁
 * @data 2019/4/15 0015
 */
public class SecurityUser extends User implements UserDetails {
    private Collection<GrantedAuthority> authorityCollection;


    /**
     * 从用户对象创建
     *
     * @param user 用户
     * @return 安全用户对象
     */
    public static UserDetails from(User user) {
        SecurityUser target = new SecurityUser();
        BeanUtils.copyProperties(user, target);
        target.authorityCollection =
                user.getAuthoritiesString() == null ? null :
                        Arrays.stream(user.getAuthoritiesString().split(ApplicationConstants.Security.AUTHORITY_DELIMITER))
                                .map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return target;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorityCollection;
    }

    @Override
    public String getUsername() {
        return getName();
    }

    @Override
    public boolean isAccountNonExpired() {
        Boolean expired = getExpired();
        return expired == null || !expired;
    }

    @Override
    public boolean isAccountNonLocked() {
        Boolean locked = getLocked();
        return locked == null || !locked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        Boolean credentialsExpired = getCredentialsExpired();
        return credentialsExpired != null && !credentialsExpired;
    }

    @Override
    public boolean isEnabled() {
        Boolean enabled = getEnabled();
        return enabled == null ? false : enabled;
    }
}
